package com.lovejes.cuniao.scheduling.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.lovejes.cuniao.scheduling.domain.BusinessConstants;
import com.lovejes.cuniao.scheduling.service.SchedulingService;
import com.lovejes.cuniao.scheduling.util.DBUtils;
import com.lovejes.cuniao.scheduling.util.OSIpUtil;
import com.lovejes.cuniao.scheduling.util.XMLUtil;


public class InitServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	private static Log log = LogFactory.getLog(InitServlet.class);
	
	@Override
	public void init() throws ServletException {
		super.init();
		BusinessConstants.IP_MAP.put("0.0.0.0", "0.0.0.0");
		BusinessConstants.IP_MAP.put("127.0.0.1", "127.0.0.1");
		
		Properties props = System.getProperties();
		String serverName = "";

		OSIpUtil osIpUtil = OSIpUtil.getInstance();
		String serverIp = osIpUtil.getLocalIP();
		String hostName = serverIp + serverName;
		hostName ="127.0.0.1";
		
		System.out.println("==== "+hostName+" begin Load Jobs ====");
		log.warn("==== "+hostName+" begin Load Jobs ====");
		
		String sql = "select ID,JOBNAME,JOBGROUP,CLASSNAME,TRIGGERNAME,TRIGGERGROUP,CRONEXPRESSION,"
			+ "HOSTNAME,STATUS,ISLOG,ISMUTEX,MAXTHREAD,JOBPARAMS"
			+ " from cn_jobconfig where hostname='"+ hostName +"' and isvalid='1' and status='1' ";
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		System.out.println("==== InitServlet now start ====");
		try {
			SchedulingService oSchedulingService = SchedulingService.getInstance();
			SchedulerFactory schedulerFactory = new StdSchedulerFactory();
			oSchedulingService.setScheduler(schedulerFactory.getScheduler());
			
			conn = DBUtils.getConnection(BusinessConstants.dburl, BusinessConstants.dbusername, BusinessConstants.dbpassword);
			
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while(rs.next()){
				String jobid = rs.getString("ID");
				String jobname = rs.getString("JOBNAME");
				String jobgroup = rs.getString("JOBGROUP");
				String classname = rs.getString("CLASSNAME");
				String triggername = rs.getString("TRIGGERNAME");
				String triggergroup = rs.getString("TRIGGERGROUP");
				String cronexpression = rs.getString("CRONEXPRESSION");
				String hostname = rs.getString("HOSTNAME");
				String islog = rs.getString("ISLOG");
				String ismutex = rs.getString("ISMUTEX");
				String maxthread = rs.getString("MAXTHREAD");
				String jobparams = rs.getString("JOBPARAMS");
				
				JobDataMap jobDataMap = new JobDataMap();
				jobDataMap.put("jobid", jobid);
				jobDataMap.put("jobgroup", jobgroup);
				jobDataMap.put("jobname", jobname);
				jobDataMap.put("hostname", hostname);
				jobDataMap.put("islog", islog);
				jobDataMap.put("ismutex", ismutex);
				jobDataMap.put("maxthread", maxthread);
				if(jobparams !=null && !"".equals(jobparams.trim())){
					try {
						Document doc = XMLUtil.str2Doc(jobparams);
						Element root = doc.getRootElement();
						List<?> eList = root.getChildren();
						for(int i=0,j=eList.size();i<j;i++){
							Element e = (Element)eList.get(i);
							String key = e.getName().toLowerCase();
							String value = e.getTextTrim();
							jobDataMap.put(key, value);
						}
					} catch (IOException e) {
						e.printStackTrace();
					} catch (JDOMException e) {
						e.printStackTrace();
					} 
				}
				
				try {
					Class<?> c = Class.forName(classname);
					JobDetail jobDetail = new JobDetail(jobid, jobgroup, c);
					jobDetail.setJobDataMap(jobDataMap);
					CronTrigger cronTrigger = new CronTrigger(triggername, triggergroup);
					CronExpression cexp = new CronExpression(cronexpression);
					cronTrigger.setCronExpression(cexp);
					
					oSchedulingService.startJob(jobDetail, cronTrigger);
					System.out.println("==== InitServlet start job:"+jobid+" ====");
					log.warn("==== InitServlet start job:"+jobid+" ====");
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				}catch (SchedulerException e) {
					e.printStackTrace();
				}
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(st != null){
				try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("==== InitServlet started ====");
		log.warn("==== InitServlet started ====");
	}

}
